from flask import Blueprint, request, session, redirect, url_for, jsonify, render_template

from config import md5_encrypt
from models import User

bp = Blueprint('login', __name__)

@bp.route('/login', methods=['GET', 'POST'])
def login():
    # 已登录
    if 'username' in session:
        return redirect(url_for('index.index'))

    if request.method == 'POST':
        data = request.json
        username = data.get('username')
        password = md5_encrypt(data.get('password'))
        user = User.query.filter_by(username=username, password=password).first()
        if user:
            session['username'] = username
            session['userid'] = user.id
            session['userip'] = user.ip
            return jsonify({'success': '登录成功'})
        else:
            return jsonify({'error': '账户名或密码不正确'})
    return render_template('/index/login.html')